import React, { useState, CSSProperties, ReactNode, createContext } from 'react'
import classNames from 'classnames'
import { MenuItemProps } from './menuItem'

type MenuMode = 'horizontal' | 'vertical'
export interface IMenuContext {
  index: string
  onSelect: (selectedIndex: string) => void
  mode: MenuMode
  defaultOpenSubMenus: string[]
}
export const MenuContext = createContext<IMenuContext | null>(null)

export interface MenuProps {
  defaultIndex?: string // active 的菜单项的索引值
  className?: string
  mode?: MenuMode //  横向或者纵向
  style?: CSSProperties // 样式 ****
  onSelect?: (selectedIndex: string) => void // 点击菜单
  defaultOpenSubMenus?: string[] // 菜单的默认打开 只在纵向模式下生效
  children?: ReactNode
}
export const FuckingMenu = ({
  className,
  mode = 'horizontal',
  style,
  defaultIndex = '0',
  onSelect,
  defaultOpenSubMenus = [], // 菜单的默认打开选项
  children
}: MenuProps) => {
  const [currentActive, setActive] = useState(defaultIndex) // 当前激活的菜单项
  // 类名
  const classes = classNames('fucking-menu', className, {
    'menu-vertical': mode === 'vertical', // 纵向
    'menu-horizontal': mode !== 'vertical' // 横向
  })
  // 点击事件
  const handleClick = (index: string) => {
    console.log('index s', index)
    setActive(index) // 设置当前激活的菜单项
    onSelect?.(index)
  }
  // 传递给子组件的 context
  const passedContext: IMenuContext = {
    index: currentActive ? currentActive : '0',
    onSelect: handleClick,
    mode,
    defaultOpenSubMenus
  }
  // 渲染子组件
  const renderChildren = () => {
    return React.Children.map(children, (child, index) => {
      const childElement = child as React.FunctionComponentElement<MenuItemProps>
      const { displayName } = childElement.type
      if (displayName && ['SubMenu', 'MenuItem'].includes(displayName)) {
        return React.cloneElement(childElement, {
          index: index.toString() // 设置子组件的索引值
        })
      } else {
        console.error('Warning: Menu has a child which is not a MenuItem component')
      }
    })
  }
  return (
    <ul
      className={classes}
      style={style}
      data-testid="test-menu" // 用于测试
    >
      <MenuContext.Provider
        value={passedContext} // context
      >
        {renderChildren()}
      </MenuContext.Provider>
    </ul>
  )
}

export default FuckingMenu
